package org.jerrymouse.jsa4j.db.kv.example.dao;

import java.util.List;

import org.jerrymouse.jsa4j.db.kv.Indexer;
import org.jerrymouse.jsa4j.db.kv.JsonUtil;
import org.jerrymouse.jsa4j.db.kv.example.entity.User;

public class UserDao extends SimpleUserDao {
	public static JsonUtil<User> jsonUtil = new JsonUtil<User>();
	private static String USER = "user";

	public void deleteUser(User user) {
		super.deleteUser(user);
		getIndexer().deleteIndex(user.getUsername(), user.getId());
	}

	private Indexer getIndexer() {
		Indexer indexer = RepositoryFactory.getIndexer(USER + ":username");
		return indexer;
	}

	public User getUserByUsername(String username) {
		List<String> keys = getIndexer().getIndexes(username);
		if (keys != null && keys.size() > 1)
			return getUser(keys.get(0));
		return null;
	}

	public User insertUser(User user) {
		super.insertUser(user);
		getIndexer().makeIndex(user.getUsername(), user.getId());
		return user;
	}

}
